/**
 * module app is program's common entry
 */
(function() {
	'use strict';
	
	define("app", function(){
		return {
			// TODO resize
			registerResize:function(){
				require(['jquery.plugin.resize'],function(resize){
					var delay = 100;
					
					jQuery(".editor-wrapper").bind("handlerResize",function(event, width, height, handler){
						event.preventDefault;
						
						var _this = this;
						var timeout = setTimeout(function(){
							handelHeight(_this, function(){
				        		if(_this.clientHeight == height){
				        			//console.log("width: "+width+", height:"+height+", handler:"+handler);
				        			jQuery('.wrapper-list').animate({'min-height' : height});
				        		}
				    		})
				    	}, delay);
					});
					
					/** listener element height */
				    function handelHeight(elem, callback){
				    	var height = 0;
				    	var timeout = setInterval(function(){
				    		jQuery(elem).data("resize_h", height);
				    		
				    		height = elem.clientHeight;
				    		if(height == jQuery(elem).data("resize_h")){
				    			clearInterval(timeout);
				    			if(callback) callback(height);
				    		}
				    	}, delay);
				    }
				});
			},
			// TODO widget
			registerWidget:function(){
				jQuery(".editor-wrapper").delegate('.widget-buttons *[data-toggle="maximize"]', "click", function (event) {
			        event.preventDefault();
			        
			        var widget = jQuery(this).parents(".widget").eq(0);
			        var button = jQuery(this).find("i").eq(0);
			        var compress = "fa-compress";
			        var expand = "fa-expand";
			        if (widget.hasClass("maximized")) {
			            if (button) {
			                button.addClass(expand).removeClass(compress);
			            }
			            widget.removeClass("maximized");
			            widget.find(".widget-body").css("height", "auto");
			        } else {
			            if (button) {
			                button.addClass(compress).removeClass(expand);
			            }
			            widget.addClass("maximized");
			            maximize(widget);
			        }
			    });
				
				jQuery(".editor-wrapper").delegate('*[data-toggle="collapse"]', "click", function (event) {
					event.preventDefault();
			        
			        var widget = jQuery(this).parents(".widget").eq(0);
			        var body = widget.find(".widget-body");
			        var button = jQuery(this).find("i");
			        	button = button.length == 0 ? widget.find(".widget-buttons i") : button;
			        var down = "fa-expand";
			        var up = "fa-compress";
			        var slidedowninterval = 300;
			        var slideupinterval = 200;
			        if (widget.hasClass("collapsed")) {
			            if (button) {
			                button.addClass(up).removeClass(down);
			            }
			            widget.removeClass("collapsed");
			            body.slideUp(0, function () {
			                body.slideDown(slidedowninterval);
			            });
			        } else {
			            if (button) {
			                button.addClass(down)
			                    .removeClass(up);
			            }
			            body.slideUp(slideupinterval, function () {
			                widget.addClass("collapsed");
			            });
			        }
				});

				jQuery(".editor-wrapper").delegate('.widget-buttons *[data-toggle="dispose"]', "click", function (event) {
			        event.preventDefault();
			        var toolbarLink = jQuery(this);
			        var widget = toolbarLink.parents(".widget").eq(0);
			        var disposeinterval = 300;
			        widget.hide(disposeinterval, function () {
			            widget.remove();
			        });
			    });
				
				jQuery(".editor-wrapper").delegate('.widget-buttons *[data-tool="append"]', "click", function (event) {
			        event.preventDefault();
			        
			        var _opts = jQuery(this).data();
			        
			        jQuery(_opts.templateTarget).template("loader",{
			        	"mode": "append",
			        	"data": {"index":jQuery("[data-dynamic-template]",_opts.templateTarget).length},
						"tempid": _opts.templateId,
						"tempurl": _opts.templatePath,
						"onLoaded": _opts.loaded
					});
			    });
				
				jQuery(".editor-wrapper").delegate('.widget-buttons *[data-tool="remove"]', "click", function (event) {
			        event.preventDefault();
			        
			        var template_target = jQuery(this).data("template-target");
			        var remove_action = jQuery(this).data("remove-action");
			      	  
			   	  	if(jQuery(".form-editor", template_target).length > 1 && isEmpty()){
			   	  		jQuery(".field-group:last", template_target).remove();
			   	  		jQuery(".form-editor:last", template_target).remove();
			   	  	}else if(jQuery(".form-editor", template_target).length > 1){
			   	  		var last = jQuery(".form-editor:last", template_target);
			   	  		var id =  last.find(":hidden[name='id']").val();
			   	  		var entity = last.data("entity");
				   	  	jQuery.ajaxsend({
							url:((remove_action?remove_action:"/miwawa/{dbname}/common/remove").replace("{dbname}", dbname)).replace("{id}",id),
							data: {
								"entityClass":entity,
								"bean":{"id":id}
							},
							success:function(data){
								if(data && data["success"]) {
									last.prev("fieldset").remove(); last.remove();
									jQuery.message.success("所选记录已删除！");
								}
							}
						});
			   	  	}
			     	  
			   	  	function isEmpty(){
			   	  		var result = false;
			   	  		jQuery(".form-editor:last", template_target).find("[required]").each(function(i,n){
			   	  			if(n.value == ""){
			   	  				result = true;
			   	  			}
			   	  		});
			   	  		return result;
			   	  	}
			    });
			},
			// TODO form
			registerForm:function(){
				require(['jquery.plugin.form','jquery.bootstrap.validator'],function(form, validator){
					jQuery.fn.extend({
						setForm:function(form, data, callback){
							var $this = this;
							if(typeof(data) == "object"){
								setFormObject();
							}else if(typeof(data) == "array"){
								setFormArray();
							}
							if(callback) callback(data);
							
							// 设置表单
							function setFormObject(){
								jQuery.each(data,function(k,v){
									jQuery("[name='"+k+"']", $this).val(v);
								});
								form.data(form.attr("name"), data.id);
							}
							
							function setFormArray(){
								
							}
						},
						foreign:function(){
							var foreign_key = this.data("foreign-key");
							var foreign_src = this.data("foreign-src");
							if(foreign_key && foreign_src){
								jQuery("[data-foreign-id]", this).val(jQuery(foreign_src).data(foreign_key));
							}
							return this;
						},
						formdata:function(){
							var data = {};
							var params = this.serializeArray(); // 序列化表单元素
							jQuery.each(params, function(index,param){
								data[param.name] = param.value;
							});
							return data;
						},
						formbean:function(entityClass){
							var data = {"entityClass":entityClass || this.attr("name"), "bean":{}};
							var params = this.serializeArray(); // 序列化表单元素
							jQuery.each(params, function(index,param){
								data["bean"][param.name] = param.value;
							});
							return data;
						},
						formSubmit:function(src, options, callback, before){
							var $form = this;
							var _url = $form.attr("action").replace("{dbname}", dbname);
							
							var _opts = jQuery.extend({},{
								url: _url,
								data: isCustomAction() ? src.formdata() : src.formbean($form.attr("name")),
								dataType: "json",
								resetForm: false,
								beforeSerialize: function($form, options) {
									return before ? window[before](src, $form) : true;
								},
								beforeSubmit: function(arr, $form, options) {
									return src.data("validate") == false ? true : validator.validate(src);
								},
								success: function(data){
									if(data){
										// 保存成功后设置表单
										src.setForm($form, data, function(result){
											// 保存成功后显示元素
											var show_target = $form.data("show-target");
											var show_checked = $form.data("show-checked");
											if(show_target && (typeof(show_target) == "object")){
												jQuery.each(show_target,function(i,target){
													jQuery(target).removeClass("hidden").show();
												});
											}else if(show_target){
												jQuery(show_target).removeClass("hidden").show();
											}
											if(show_checked){
												jQuery(show_checked).each(function(i, check){
													if(check.checked){
														show_target = jQuery(check).data("show-target");
														jQuery(show_target).removeClass("hidden").show();
													}
												});
											}
											// 保存成功后执行回调
											if(callback) callback(result);
										});
									}else{
										// 保存失败提醒
									}
								}
							}, options);
							
							$form.ajaxSubmit(_opts);
							
							/* 是否是自定义Actioin */
							function isCustomAction(){
								return $form.data("custom-action") || false;
							}
						},
						loadform:function(method, params){
							if (typeof method == 'string') {
								return this.loadform.methods[method](this, params);
							}
						}
					});
					
					jQuery.fn.loadform.methods = {
						"many":function($this, helper){
					  	  	$this.searched({offset:0,limit:0}, {
								success: function(data, status, xhr){
									createTemplate(jQuery.extend({ "templateData": data.rows }, $this.data()), helper);
								}
							});
						},
						"load":function($this, options){
							createTemplate(jQuery.extend({ "templateTarget": $this }, options), options.templateHelper);
						},
						"data":function($this, data){
							jQuery.each(data, function(key, val){
								jQuery("#"+key, $this).text(val);
							});
						},
						"empty":function($this, options){
							createTemplate(jQuery.extend({ "templateData": options.templateData }, $this.data()), options.templateHelper);
						}
					};
					
					function createTemplate(options, helper){
						jQuery(options.templateTarget).template("loader",{
							"data": options.templateData,
							"tempid": options.templateId,
							"tempurl": options.templatePath,
							"helpers": helper,
							"onLoaded": options.onLoadSuccess
						});
					}
				});
			},
			// TODO table
			registerTable:function(){
				require(['jquery.bootstrap.table'],function(table){ table(); });
			}
		};
	});
})(this);

// TODO page switch on ajaxload
//----------------------------------- 
(function(window, document, $, undefined){
	'use strict';
	
	// 打开新增界面
	window["handlerCreate"] = function(button, rowid, callback){
		var _opts = jQuery(button).data();
		
		if(rowid && _opts.notable){
			jQuery(_opts.tableSource).data("selectedId", rowid);
		}else if(rowid){
			jQuery(_opts.tableSource).data("selectedRow", jQuery(_opts.tableSource).bootstrapTable("getRowByUniqueId",rowid));
		}
		
		if(callback && typeof(callback) == "string") {
			window[callback](button);
		}else if(callback && typeof(callback) == "function"){
			callback(button);
		}else{
			var page = _opts.editorPage || "add.html";
			var path = _opts.editorPath || "editor";
			var open = _opts.editorOpen || "editor-wrapper-open";
			
			jQuery(".editor-wrapper").template("loader",{"tempurl": (path + "/" + page)}).parent().addClass(open);
			
			jQuery('[data-default-user]').each(function(i, input) {
				jQuery(input).val(getStorage("sessionStorage", "session.user.id"));
				jQuery("[name='username']").val(getStorage("sessionStorage", "session.user.name"));
			});
		}
	}
	
	// 取消新增界面
	window["handlerCancel"] = function(button) {
		jQuery(".wrapper").removeClass("editor-wrapper-open");
		
		setTimeout(function(){
			jQuery(".tooltip").remove();
			jQuery(".editor-wrapper").empty();
		},400);
		
		jQuery(jQuery(button).data("refresh-table")).bootstrapTable("refresh");
	}
	
	// 列表删除
	window["handlerRemove"] = function(button, rowid){
		var _opts = jQuery(button).data();
		var $form = jQuery(_opts.formSource);
		var $table = jQuery(_opts.tableSource);
		var $param = $form.attr("name") ? {
			"entityClass":$form.attr("name"),
			"bean":{"id":rowid}
		}:{"id":rowid};
		
		jQuery.message.confirm("删除该记录后，所有相关数据将一并删除，并无法恢复，确定要删除该记录吗？",function(confirm){
			if(confirm){
				jQuery.utils.loading("正在删除数据，请稍后...", "show");
				jQuery.ajaxsend({
					url: $form.attr("action").replace("{dbname}", dbname),
					data: $param,
					success:function(data){
						if(data && data["success"]) {
							jQuery(button).tooltip("destroy");
							$table.bootstrapTable("remove",{field:"id",values:[rowid]});
							$table.bootstrapTable("refresh");
							jQuery.utils.loading(null, "hide");
							jQuery.message.success("所选记录已删除！");
						}
					}
				});
			}
		});
	}
	
	// 列表还原
	window["handlerReback"] = function(button, rowid){
		var _opts = jQuery(button).data();
		var $form = jQuery(_opts.formSource);
		var $table = jQuery(_opts.tableSource);
		jQuery.ajaxsend({
			url: $form.attr("action").replace("{dbname}", dbname),
			data: _opts.custom ? {
				"id":rowid,"status":"0"
			}:{
				"entityClass":$form.attr("name"),
				"bean":{"id":rowid,"status":"0"}
			},
			success:function(data){
				if(!data.error) {
					jQuery(button).tooltip("destroy");
					$table.bootstrapTable("remove",{field:"id",values:[rowid]});
					$table.bootstrapTable("refresh");
					jQuery.message.success("所选记录已还原！");
					if(_opts.callback) window[_opts.callback](data);
				}else{
					jQuery.message.warning(data.error);
				}
			}
		});
	}
	
	// 更新数据状态
	window["handlerModify"] = function(button, rowid, status){
		var _opts = jQuery(button).data();
		var $form = jQuery(_opts.formSource);
		var $table = jQuery(_opts.tableSource);
		jQuery.ajaxsend({
			url: $form.attr("action").replace("{dbname}", dbname),
			data: _opts.custom ? {
				"id":rowid,"status":status
			}:{
				"entityClass":$form.attr("name"),
				"bean":{"id":rowid,"status":status}
			},
			success:function(data){
				if(!data.error) {
					jQuery(button).tooltip("destroy");
					$table.bootstrapTable("refresh");
					if(_opts.callback) window[_opts.callback](data);
				}else{
					jQuery.message.warning(data.error);
				}
			}
		});
	}
})(window, document, window.jQuery);
